function CreateWorld(test) {
    //读取本地设置加载存档
    let preloadData = World.Core.GetGlobalVars("CreateHostPreloadData");

    if (preloadData != null) {
        preloadData = JSON.parse(preloadData);
    } else {
        preloadData = {};
    }

    //读取数据
    WGame.SaveName = preloadData.SaveName ?? "Default";

    LoadGameData(WGame.SaveName);
}

function LoadGameData(saveName) {
    Debug.LogError("LoadGameData: " + saveName);

    //存档目录
    let rootSavePath = `SaveData`;
    if (World.Core.ExistHostFile(`${rootSavePath}/`) == false) {
        World.Core.WriteHostFile(`${rootSavePath}/`);
    }

    //读取存档
    WGame.SavePath = `${rootSavePath}/${saveName}`;

    let isNewData = false;

    if (World.Core.ExistHostFile(`${WGame.SavePath}/`) == false) {
        isNewData = true;

        //存档不存在，新建存档
        World.Core.WriteHostFile(`${WGame.SavePath}/`);

        //创建数据库
        World.SQLite.Create(`${WGame.SavePath}/Database.db`);
    }

    //加载存档
    WGame.SaveDB = World.SQLite.Connect(`${WGame.SavePath}/Database.db`);
    if (WGame.SaveDB == null) {
        Debug.LogError("LoadGameData: Error");
        Disconnect();
        return;
    }

    //新存档
    if (isNewData) {
        Debug.LogError("isNewData: " + isNewData);

        WGame.SaveDB.Begin();

        //World
        WGame.SaveDB.Execute(`
            CREATE TABLE World (
                Version INTEGER DEFAULT 1,
                RunTime INTEGER DEFAULT 0,
                Time TEXT DEFAULT '12|0',
                Weather INTEGER DEFAULT 0
            );
        `);
        WGame.SaveDB.Execute(`
            INSERT INTO World DEFAULT VALUES;
        `);

        //Account
        WGame.SaveDB.Execute(`
            CREATE TABLE Account (
                Account TEXT,
                Password TEXT,
                UUID TEXT,
                Address TEXT,
                RegisterTime TEXT,
                LoginTime TEXT,
                Name TEXT,
                Level INTEGER DEFAULT 1,
                EXP INTEGER DEFAULT 0,
                Health INTEGER DEFAULT 100,
                Armour INTEGER DEFAULT 100,
                Cash INTEGER DEFAULT 0,
                Skin INTEGER DEFAULT 0,
                Position TEXT DEFAULT '0|0|0',
                Kills INTEGER DEFAULT 0,
                Deaths INTEGER DEFAULT 0,
                Hunger INTEGER DEFAULT 100,
                Thirst INTEGER DEFAULT 100,
                Stamina INTEGER DEFAULT 0,
                Wanted INTEGER DEFAULT 0,
                Company INTEGER DEFAULT -1,
                CompanyLevel INTEGER DEFAULT -1,
                AdminLevel INTEGER DEFAULT 0
            );
        `);
        WGame.SaveDB.Commit();
    }

    //SQLite
    let worldQuery = WGame.SaveDB.Query("SELECT * FROM World;");

    WGame.RunTime = worldQuery.Get("RunTime");

    let worldTimeData = worldQuery.Get("Time").split('|');
    World.Core.SetWorldTime(parseInt(worldTimeData[0]), parseInt(worldTimeData[1]));
    World.Core.SetWorldWeather(worldQuery.Get("Weather"));

    //Other
    World.Vehicle.Create(12, Vector(20, 10, 20));
    World.Vehicle.Create(13, Vector(25, 10, 20));
    World.Vehicle.Create(11, Vector(35, 10, 25));
}

function SaveGameData() {
    Debug.LogError("SaveGameData: " + WGame.SaveName);

    //保存存档
    WGame.SaveDB.Begin();
    WGame.SaveDB.Execute(`UPDATE World SET RunTime = ${WGame.RunTime};`);
    let worldTime = World.Core.GetWorldTime();
    WGame.SaveDB.Execute(`UPDATE World SET Time = ${worldTime.Hour}|${worldTime.Minute};`);
    WGame.SaveDB.Execute(`UPDATE World SET Weather = ${World.Core.GetWorldWeather()};`);
    WGame.SaveDB.Commit();
}

/**
 * @param {World.Player} player
 * @param {string} account
 * @param {string} password
 */
function PlayerAccount(player, account, password) {
    if (player.Data.IsAccountProcessing) return false;
    else if (player.Data.IsLoggedIn) return false;

    account = account.trim();

    player.Data.IsAccountProcessing = true;
    //Debug.LogError("PlayerAccount: " + account + ", " + password);

    //读取账号数据
    let query = WGame.SaveDB.Query(`SELECT * FROM Account WHERE Account = '${account}';`);

    //账号不存在
    let isNewAccount = false;

    if (query.HasData() == false) {
        isNewAccount = true;

        WGame.SaveDB.Begin();
        WGame.SaveDB.Execute(`
            INSERT INTO Account ( Account, Password, UUID, Address, RegisterTime, Name ) 
            VALUES ( 
                '${account}',
                '${Encrypt.SHA256Encrypt(password)}',
                '${player.UUID}',
                '${player.Address}',
                '${GetTimestamp()}',
                'Player#${GenerateUUID().substring(0, 4)}'
            );`
        );
        WGame.SaveDB.Commit();
    }
    //账号存在
    else {
        if (query.Get("Password") != Encrypt.SHA256Encrypt(password)) {
            player.Data.IsAccountProcessing = false;
            player.Subtitle("登录失败，账号或密码错误！");
            return false;
        }
    }

    //登录成功
    WGame.SaveDB.Begin();
    WGame.SaveDB.Execute(`UPDATE Account SET LoginTime = '${GetTimestamp()}' WHERE Account = '${account}';`);
    WGame.SaveDB.Commit();

    player.Data.Account = account;
    player.Data.IsLoggedIn = true;

    ReadPlayerData(player);
    SavePlayerData(player);

    if (isNewAccount) {
        player.Subtitle("注册成功，欢迎来到后世界！");
    } else {
        player.Subtitle("登录成功，欢迎回到后世界！");
    }

    player.NetworkRPC("account_panel_hide");

    player.Data.IsAccountProcessing = false;

    OnPlayerAccountLogged(player);

    return true;
}

/**
 * 
 * @param {World.Player} player 
 */
function SpawnPlayerCharacter(player) {
    let character = World.Character.Create(0, Misc.StringToVector(player.Data.SaveData.Position), 0, player.Data.SaveData.Skin);
    player.SetEntity(character, true);
}

/**
 * 
 * @param {World.Player} player 
 */
function ReadPlayerData(player) {
    /*let account = player.Data.Account;
    let query = WGame.SaveDB.Query(`SELECT * FROM Account WHERE Account = '${account}';`);

    //DefaultData
    if (player.Data.SaveData.Skin == null)
        player.Data.SaveData.Skin = Random.RangeInt(0, 100);

    if (player.Data.SaveData.Position == null)
        player.Data.SaveData.Position = Misc.VectorToString(Vector(0, 0, 0));*/
}

/**
 * 
 * @param {World.Player} player 
 */
function SavePlayerData(player) {
    if (player.Data.IsLoggedIn == false) return;

    let userName = player.Data.UserName;
    let playerDataPath = `${WGame.SavePath}/Player/${userName}.json`;

    if (player.Entity != null) {
        player.Data.SaveData.Position = Misc.VectorToString(player.Entity.Pos);
    }

    let dataJson = JSON.stringify(player.Data.SaveData);

    World.Core.WriteHostFile(playerDataPath, dataJson);

    Debug.LogError("SavePlayerData: " + userName);
}

function Message(string, richName = "系统消息") {
    World.Core.Message(`[b][color=#ffffff][${richName}][/color][/b] ${string}`);
}

function MessagePlayer(player, string, richName = "系统消息") {
    player.Message(`[b][color=#ffffff][${richName}][/color][/b] ${string}`);
}